package com.zelin.listener;


import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by WF on 2020/12/16 17:09
 */
public class TestMongoDB {

    private MongoClient mongoClient;
    private MongoCollection<Document> collection;
    @Before
    public void init(){
        //1.得到mongo的客户端
        mongoClient = new MongoClient("192.168.25.143");
        //2.得到mongo的数据库
        MongoDatabase spitdb = mongoClient.getDatabase("spitdb");
        //3.得到集合（表）
        collection = spitdb.getCollection("spit");
    }

    //1.查询所有
    @Test
    public void test01(){
        //1.1)查询所有的文档
        FindIterable<Document> documents = collection.find();
        //1.2)打印文档内容
        printInfo(documents);
        //1.3)关闭客户端
        mongoClient.close();
    }
    //2.打印信息
    private void printInfo(FindIterable<Document> documents) {
        for (Document doc : documents) {
            Object id = doc.get("_id");
            Object content = doc.get("content");
            Object visits = doc.get("visits");
            Object userid = doc.get("userid");
            Object nickname = doc.get("nickname");
            System.out.println("id = " + id);
            System.out.println("content = " + content);
            System.out.println("visits = " + visits);
            System.out.println("userid = " + userid);
            System.out.println("nickname = " + nickname);
            System.out.println("-----------------------------------------------");
        }
    }

    //3.按照条件查询{"visits:{$gt:1000}}
    @Test
    public void test02(){
        //3.1)定义查询条件
        Bson bson = new BasicDBObject("visits",new BasicDBObject("$gt",1000));
        //3.2)开始查询
        FindIterable<Document> documents = collection.find(bson);
        printInfo(documents);
        mongoClient.close();
    }

    //4.添加一条
    @Test
    public void test03(){
        //4.1)定义要添加的记录
        Map<String, Object> map = new HashMap<>();
        map.put("_id","333");
        map.put("content","新增一条数据..");
        map.put("userid","1020");
        map.put("visits",1001);
        map.put("nickname","小明");
        map.put("parentid","2");
        //4.2)定义要添加的文档（包含数据）
        Document doc = new Document(map);
        //4.3)添加记录
        collection.insertOne(doc);
        //4.4)关闭
        mongoClient.close();
    }

}
